package com.TestSocket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
 

public class TestSocketService extends Thread{
	public interface OnSocketService{
		void onSocketServiceClientExit(String msg);
		void onSocketServiceClientConnect(String msg);
	}
	
	public final static int EXIT_CODE=10;
	public final static int CONNECT_CODE=11;
	public OnSocketService mOnSocketListen;
	public Context mCtx;
	public serviceHandler mSrvHander;
	public final static String Tag="TestSocketService";
	public List<Socket> mlstSocket = new ArrayList<Socket>();
	public static final int Connect_Port = 9999;
	public ServerSocket server = null;
	public ExecutorService mExeCutorService = null;	//Thread pool
	
	public TestSocketService(Context ctx,OnSocketService listen)
	{
		mOnSocketListen = listen;
		mCtx = ctx;
		mSrvHander = new serviceHandler();
	}
	public void run(){
		try {
			server = new ServerSocket(Connect_Port);
			mExeCutorService = Executors.newCachedThreadPool();
			Socket client = null;
			while(true){
				client = server.accept();
				mlstSocket.add(client);
				mExeCutorService.execute(new ServiceClient(client));
				
				String msg = "One Client connect:"+client.getLocalSocketAddress().toString()+",Now has "
						+mlstSocket.size()+" client";
				Message message = new Message();
				message.obj = msg;
				message.what = CONNECT_CODE;
				mSrvHander.sendMessage(message); 
				
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public class ServiceClient implements Runnable{
		private Socket socket;
		private BufferedReader in = null;
		private String msg = ""; 
		public ServiceClient(Socket socket){
			this.socket = socket;
			try {
				in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//				msg = "user" +this.socket.getInetAddress() + "come toal:"  
//       	                 +mlstSocket.size();  
			//	TestSocketActivity.mHandService.sendEmptyMessage(100);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		@Override
		public void run() {
			// TODO Auto-generated method stub
            try {  
                while(true) {  
                    if((msg = in.readLine())!= null) {  
                        if(msg.equals("exit")) {   
                            mlstSocket.remove(socket);  
                            in.close();  
                            msg = "user:" + socket.getInetAddress()  
                                + "exit total:" + mlstSocket.size();  
                            socket.close();  
                            
                            mSrvHander.sendEmptyMessage(EXIT_CODE);
                            break;  
                        } else {  
                            msg = "server---"+"the client:"+socket.getInetAddress() + "send the message:" + msg;  
                            Log.v(Tag, msg); 
                        }  
                    }  
                }  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
		}
	}
	
	public class serviceHandler extends Handler{
		@Override
		public void handleMessage(Message msg)
		{
			if(msg.what == EXIT_CODE)
			{
				String message="One Client Exit!";
				if(mOnSocketListen!=null)
				{
					mOnSocketListen.onSocketServiceClientExit(message);
				} 
			}else if(msg.what == CONNECT_CODE){
				if(mOnSocketListen!=null)
				{
					String message = (String) msg.obj;
					mOnSocketListen.onSocketServiceClientConnect(message);
				}
			}
			super.handleMessage(msg);
		}
	}
	
}
